import java.net.*;
import java.io.*;

public class NCTServerThread extends Thread {
    private Socket socket = null;
    PrintWriter out;
    BufferedReader in;
    String playerName;

    public NCTServerThread(Socket socket) {
    	super("NCTServerThread");
    	this.socket = socket;
    	try {
    		out = new PrintWriter(socket.getOutputStream(), true);
    		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		playerName = in.readLine();
    		
    	} catch (IOException e) {
    	    e.printStackTrace();
    	}
    }
    
    public String getPlayerName(){
    	return playerName;
    }

    public void run() {

	try {
	    String inputLine, outputLine;

	    while ((inputLine = in.readLine()) != null) {
	    	if(inputLine.startsWith("SyncMe")){
	    		/*out.println("sync");
	    		out.close();
	    		ObjectOutputStream objectStream = new ObjectOutputStream(socket.getOutputStream());
	    		objectStream.writeObject(Game.getGame().cardtable);
	    		objectStream.flush();
	    		objectStream.close();
	    		out = new PrintWriter(socket.getOutputStream(), true);*/
	    		//sync all Counters
	    		CardTable help = Game.getGame().cardtable;
	    		Counter[] synC = help.getAllCounters();
	    		for(Counter tmp:synC){
	    			out.println("createcounter " + tmp.getName() + " " + tmp.getX() + " " + tmp.getY());
	    			out.println("inc " + tmp.getName() + " " + tmp.getValue());
	    		}
	    		//sync all stacks
	    		CardStack[] synS = help.getAllStacks();
	    		for(CardStack tmp:synS){
	    			StringBuffer msg = new StringBuffer("createstack " + tmp.getName() + " " + tmp.getX() + " " + tmp.getY());
	    			Card[] cards = tmp.revealTop_old(tmp.getNumberOfCards());
	    			for(int i = 0; i<tmp.getNumberOfCards();++i){
	    				msg.append((cards[i]).getName());
	    			}
	    			out.println(msg.toString());
	    		}
	    		
	    	}
	    	else if(inputLine.startsWith("shuffle")){
	    		int endOfName = inputLine.lastIndexOf(' ');
	    		String name = inputLine.substring(8,endOfName);
	    		String player = inputLine.substring(endOfName+1,inputLine.length());
	    		int[] shuf = Game.getGame().cardtable.getCardStack(name).createShuffle();
	    		StringBuffer msg = new StringBuffer("shuffled ").append(name+" ").append(player +" ");
	    		for(int i = 0; i< shuf.length;i++){
	    			msg.append(shuf[i]).append(" ");
	    		}
	    		Game.getGame().server.sendToAll(msg.toString());
	    		
	    	}
	    	else{
	    		Game.getGame().server.sendToAll(inputLine);
	    	}
			if (inputLine.equals("quit"))
			    break;
	    }
	    out.close();
	    in.close();
	    socket.close();

	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
    
    public void send(String pMsg){
    	out.println(pMsg);
    }
}
